// pages/orderList/index.js
import {
  ApiOrderList,
  ApiOrderPay,
  ApiCancelPay,
  getCustomerPhone,
  setPayExtend
} from '../../api/index'
import {
  debounce
} from "../../utils/index"
const app = getApp()
let {
  baseUrl,
  commonUpdate,
  commonUpload
} = app.globalData
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseUrl,
    commonUpload,
    status: "1",
    activeNames: [],
    statusFormatter: [{
      label: '待支付',
      value: '1'
    }, {
      label: '待接单',
      value: '2'
    }, {
      label: '已接单',
      value: '3'
    }, {
      label: '已出发',
      value: '4'
    }, {
      label: '已上门',
      value: '5'
    }, {
      label: '已完成',
      value: '6'
    }, {
      label: '已取消',
      value: '7'
    }, {
      label: '退款中',
      value: '8'
    }],

    steps: [{
        text: '待接单',
      },
      {
        text: '已接单',
      },
      {
        text: '已出发',
      },
      {
        text: '已上门',
      },
      {
        text: '已完成',
      },
    ],
    dataList: [],
    inProgress: "",
    complete: '',
    total: '',
    active: '进行中',
    List: [],
    time: 36000,
    timeData: {}
  },

  iconClick(e) {
    let val = e.currentTarget.dataset.v.id
    /*   this.setData({
        'e.currentTarget.dataset.v.showText': true
      }) */

    let val1 = this.data.dataList.findIndex(item => {
      if (item.id == val) {
        return item
      }
    })

    this.setData({
      ['dataList[' + val1 + '].showText']: true
    })
    setTimeout(() => {
      this.setData({
        ['dataList[' + val1 + '].showText']: false
      })
    }, 2000);
  },
  //立即支付
  setPayExtendButton: debounce(function (e) {
    {
      setPayExtend(e.currentTarget.dataset.v[0].id).then(res => {
        if (res.code == '200') {
          let that = this
          wx.requestPayment({
            ...res.data,
            success(res) {
              /*      app.clearStatistics() */
              wx.showModal({
                title: '支付成功',
                showCancel: false,
                success(res) {
                  /*   this.setData({
                      active: '全部'
                    }) */
                  that.getOrderList(that.data.active)
                  /*   if (that.data.luckyDrawTime) {
                      wx.redirectTo({
                        url: '/pages/activity/index?router=/activity/paymentDraw',
                      })
                    } else {
                      pathBack("pages/user/payOrInvoice/pay/index", 1)
                    } */
                }
              })
            },
            fail(res) {
              /*      console.log('1111', res) */
              wx.showModal({
                title: '支付失败',
                showCancel: false
              })
            }


          })
        }
      })
    }
  }, 1000, true),



  onSupplementary(e) {
    let val = e.currentTarget.dataset.v.id
    let val1 = this.data.dataList.findIndex(item => {
      if (item.id == val) {
        return item
      }
    })
    this.setData({
      ['dataList[' + val1 + '].activeNames']: e.detail
    })
  },
  onChangeTime(e) {
    setTimeout(() => {
      this.getOrderList(this.data.active)
    }, 10000);
    console.log('finished')
  },

  onChange(e) {
    if (timer.minutes < 10) {
      timer.minutes = '0' + timer.minutes
    }
    if (timer.seconds < 10) {
      timer.seconds = '0' + timer.seconds
    }
    this.setData({
      timeData: timer,
    });
  },
  //下载报告
  downloadReport(e) {
    let url = e.currentTarget.dataset.v.service_file
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        wx.shareFileMessage({
          filePath: filePath,
          success() {},
          fail: console.error,
        })
        /*   wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            },
            fail: function (res) {
              console.log(res);
            },
            complete: function (res) {
              console.log(res);
            }
          }) */
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      complete: function (res) {},
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.data && options.data.length > 0) {
      this.getOrderList(options.data)
      this.setData({
        active: options.data
      })
    }
    /*  else {
       this.getOrderList('全部')
     } */
    /*    this.getOrderList('全部') */
  },
  /*   onShow() {
      this.getOrderList('全部')
    }, */


  /*    handleGetPhone(e) {
       const that = this
       wx.showModal({
         title: "是否确认拨打电话？",
         success(res) {
           if (res.confirm) {
             getCustomerPhone().then(res => {
               that.onSelect(res.data)
             })
   
           }
         }
   
       })
     },
     //拨号成功
     onSelect(event) {
       const tel = event
       wx.makePhoneCall({
         phoneNumber: tel,
         success: function () {
           console.log("拨号成功！")
         },
         fail: function () {
           console.log("拨号失败！")
         }
       })
     }, */
  onShow() {

    if (typeof this.getTabBar === "function" &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    console.log(this.data.active)
    this.getOrderList(this.data.active)
  },
  //申请延期
  applyExtension(e) {
    wx.navigateTo({
      url: `/pages/applyExtension/index?data=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  //拿到订单列表数据

  getOrderList(val) {
    ApiOrderList({
      status: val
    }).then(res => {
      if (res.code == 200) {
        res.data.forEach(item => {
          if (item.extend_order.length > 0) {
            item.extend_order.forEach(i => {
              i.picArr = i.pic.split(',')
            })
            item.showText = false
            item.activeNames = ['1']
            //加上费用
            item.amount = (Number(item.extend_order[0].amount) + Number(item.amount)).toFixed(2)
          }
          //添加字段
          this.checkStatus(item)
        })

        this.setData({
          dataList: res.data,
          complete: res.complete,
          inProgress: res.inProgress,
          total: res.total
        })
      }
    })
  },

  //改变状态
  checkStatus(item) {
    this.data.statusFormatter.forEach(statusItem => {
      if (item.status == statusItem.value) {
        item.statusLabel = statusItem.label
      }
    })
  },
  // 过滤
  filterValue(val, item) {
    if (val == '全部') {
      this.data.List.push(item)
    } else {
      if (item.statusLabel == val) {
        this.data.List.push(item)
      }
    }

  },
  //切换页面
  onChangeTab(e) {
    console.log(e)
    this.setData({
      active: e.detail.name
    })
    this.getOrderList(e.detail.name)
  },
  //跳转到订单详情
  bindClickDetail(e) {
    wx.navigateTo({
      url: `/pages/orderListDetail/index?data=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  //继续付款
  continuePay: debounce(function (e) {
    ApiOrderPay(e.currentTarget.dataset.v.id).then(res => {
      if (res.code == '200') {
        let that = this
        wx.requestPayment({
          ...res.data,
          success(res) {
            /*       app.clearStatistics() */
            wx.showModal({
              title: '支付成功',
              showCancel: false,
              success(res) {
                this.setData({
                  active: '全部'
                })
                that.getOrderList('全部')
                /*   if (that.data.luckyDrawTime) {
                    wx.redirectTo({
                      url: '/pages/activity/index?router=/activity/paymentDraw',
                    })
                  } else {
                    pathBack("pages/user/payOrInvoice/pay/index", 1)
                  } */
              }
            })
          },
          fail(res) {
            console.log('1111', res)
            wx.showModal({
              title: '支付失败',
              showCancel: false
            })
          }


        })
      }
    })
  }, 1000, true),
  //取消订单
  cancelPay(e) {
    wx.navigateTo({
      url: `/pages/cancelPayOrder/index?data=${JSON.stringify(e.currentTarget.dataset.v.id)}`,
    })



  },
  //立即评价
  evaluation(e) {
    wx.navigateTo({
      url: `/pages/evaluation/index?id=${JSON.stringify(e.currentTarget.dataset.v)}`,
    })
  },
  //查看评价
  SearchEvaluation(e) {
    wx.navigateTo({
      url: `/pages/searchEvaluation/index?id=${e.currentTarget.dataset.v.id}`,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})